import { Select } from 'antd';
import Graphin, { Utils } from '@antv/graphin';
import React from 'react';
import EquityGraph from './components/graph';
import SearchBox from '@/components/Search/SearchBox';
import BiSearchBox from '@/components/Search/BiSearchBox';
import iconLoader from '@antv/graphin-icons';
import '@antv/graphin-icons/dist/index.css';
import { getAssociateEntity, getAssociatePath } from '@/services/zhirong/associate';
import ProCard from '@ant-design/pro-card';
import AdvanceSearchBox from '@/components/Search/AdvanceSearchBox';
import CompanyInfo from './components/companyInfo';
import GraphLayout from '@/components/graphLayout';
import { KeepAlive } from 'umi'

const { fontFamily } = iconLoader();
const icons = Graphin.registerFontFamily(iconLoader);
const searchOptions = [
  {
    name: '实体查询',
    value: '实体查询',
  },
  {
    name: '路径查询',
    value: '路径查询',
  },
  // {
  //   name: '多跳查询',
  //   value: '多跳查询',
  // },
];

const parseGraphData = (data, centerID) => {
  const nodeParser = (node) => {
    return {
      id: node.id,
      style: {
        label: {
          value: node.name,
        },
        icon: {
          fontFamily,
          type: 'font',
          value: node.category === 'E' ? icons.company : icons.user,
          fill: centerID?.includes(node.id) ? 'red' : '#3da2ff',
          size: 23,
          fillOpacity: 0.8,
        },
        keyshape: {
          size: 32,
          fill: centerID?.includes(node.id) ? 'red' : '#3da2ff',
          stroke: centerID?.includes(node.id) ? 'red' : '#3da2ff',
          lineWidth: 3,
        },
      },
    };
  };
  const edgeParser = (edge) => {
    return {
      id: edge.id,
      source: edge.source,
      target: edge.target,
      style: {
        label: {
          value: edge.label,
          fill: '#838383',
        },
        keyshape: {
          stroke: '#999999',
          // lineWidth: 4,
        },
      },
    };
  };

  console.log('dad', data)
  return {
    nodes: data?.data?.nodes?.map(nodeParser),
    edges: data?.data?.links?.map(edgeParser),
  };
};
class MultiQuery extends React.Component {
  constructor(props) {
    super(props);
    this.state = { data: Utils.mock(0).circle().graphin(), search: '实体查询', loading: false }; // default graph
  }

  handleChange = (e) => {
    this.setState({ ...this.state, search: e });
  };

  //让外层容器瞬间loading实现强制刷新
  refresh = () => {
    this.setState({ ...this.state, loading: true }, () => {
      this.setState({ ...this.state, loading: false });
    });
  };


  onAdvanceSubmit = (value) => {
    this.setState({
      ...this.state,
      focusNodeId: value[0].eid,
      name: value[0].FullName,
      loading: true,
    });
    let graphData = {};
    let count = value.length - 1;
    value.forEach((e, index) => {
      if (index === value.length - 1) return;
      getAssociatePath({
        entityA: e.eid ?? e.id,
        entityB: value[index + 1]?.eid ?? value[index + 1]?.id,
      }).then((res) => {
        console.log("多跳查询的res>>>>>", res.data?.data)
        if (!res.data?.data?.nodes || !res.data?.data?.links) return;
        //  graphData.nodes?.push(...res);
        graphData = { ...res.data };
        count--;
        if (count === 0) {
          this.setState({
            ...this.state,
            data: parseGraphData(
              graphData,
              value.map((v) => v.id ?? v.eid),
            ),
            loading: false,
          });
        }
      });
    });
  };

  searchBox = {
    实体查询: (
      <SearchBox
        onSubmit={(value) => {
          this.setState({
            ...this.state,
            focusNodeId: value.eid,
            name: value.FullName,
            loading: true,
          });
          getAssociateEntity({
            centerId: value.eid,
            // dateFrom: '2018-01-01',
            // dateTo: '2018-12-31',
          }).then((obj) => {
            console.log("实体查询的obj???>>>>", obj)

            this.setState({
              ...this.state,
              data: parseGraphData(obj.data, [value.eid]),
              upd: this.upd,
              loading: false,
            });
          });
        }}
        advices={[
          {
            FullName: '招商银行股份有限公司',
            eid: 'c97ca8d1-ae17-43e4-8bac-b4b22051484c',
            status: '存续（在营、开业、在册）',
          },
          // {
          //   eid: 'ad33c2b1-97c7-4b99-b224-b25275cfc9b4',
          //   FullName: '平安银行股份有限公司',
          //   status: '存续（在营、开业、在册）',
          // },
        ]}
      />
    ),
    路径查询: (
      <BiSearchBox
        onSubmit={(value) => {
          console.log("路径查询", value)


          this.setState({
            ...this.state,
            focusNodeId: value.eid,
            name: value.enterpriseB.FullName,
            loading: true,
          });
          getAssociatePath({
            entityA: value.enterpriseB.eid,
            entityB: value.enterpriseA.id,
            // direction: 1,
            // dateFrom: '2018-01-01',
            // dateTo: '2018-12-31',
          }).then((obj) => {
            console.log("路径查询的obj???>>>>", obj)
            this.setState({
              ...this.state,
              data: parseGraphData(obj.data, [value.enterpriseA.eid, value.enterpriseB.eid]),
              upd: null,
              loading: false,
            });
          });
        }}
        list={this.state?.data.nodes}
        advices={[
          {
            FullName: '招商银行股份有限公司',
            eid: 'c97ca8d1-ae17-43e4-8bac-b4b22051484c',
            status: '存续（在营、开业、在册）',
          },
        ]}
      />
    ),
    // 多跳查询: (
    //   <AdvanceSearchBox
    //     onSubmit={(value) => {
    //       console.log("多跳查询", value)
    //       // this.setState({
    //       //   ...this.state,
    //       //   name: '',

    //       // });
    //       this.onAdvanceSubmit(value)
    //     }}
    //     advices={[
    //       {
    //         FullName: '招商银行股份有限公司',
    //         eid: 'c97ca8d1-ae17-43e4-8bac-b4b22051484c',
    //         status: '存续（在营、开业、在册）',
    //       },
    //     ]}
    //   />
    // ),
  };

  async upd(id) {
    const rt = await getAssociateEntity({
      centerID: id,
      dateFrom: '2018-01-01',
      dateTo: '2018-12-31',
    });
    // console.log('upd',rt)
    return parseGraphData(rt.data);
  }

  render() {
    return (
      <ProCard direction="column" ghost>
        <ProCard
          gutter={8}
          style={{
            paddingBottom: "3em",
            marginBottom: '1em',
            borderRadius: '8px',
            height: "155px"
          }}
          layout="center"
          title={<b style={{ fontSize: '18px' }}>多元查询</b>}
        >
          <ProCard layout="center" bodyStyle={{ padding: '0' }}>
            <KeepAlive>
              <Select
                options={searchOptions}
                onChange={this.handleChange}
                defaultValue="实体查询"
                style={{ marginBottom: '2.5rem' }}
              ></Select>
            </KeepAlive>
            {this.searchBox[this.state.search]}
          </ProCard>
        </ProCard>
        <GraphLayout
          leftSpan={15}
          rightSpan={9}
          leftChildren={
            <ProCard
              style={{ height: '90vh', borderRadius: '8px' }}
              loading={this.state.loading}
              layout="center"
              width="100%"
            >
              {/* <KeepAlive> */}
              <EquityGraph
                data={this.state.data}
                expander={this.state.upd}
                setFocusNodeId={(focusNodeId) => this.setState({ ...this.state, focusNodeId })}
                refresh={this.refresh}  //刷新函数
              ></EquityGraph>
              {/* </KeepAlive> */}
            </ProCard>
          }
          rightChildren={
            <ProCard style={{ height: '90vh', borderRadius: '8px' }}>
              <KeepAlive>
                <CompanyInfo focusNodeId={this.state.name}></CompanyInfo>
              </KeepAlive>
            </ProCard>
          }
        ></GraphLayout>
      </ProCard>

    );
  }
}

export default MultiQuery;